package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;


/**
 * http客户端工具
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 员工添加
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //创建employee对象,只要这个是和数据库表对应,进行操作
        Employee employee = new Employee();
        //拷贝数据,employeeDTO-->employee
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置employee中其他属性的值
        //设置密码默认123456
        String md5Pass = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8));
        employee.setPassword(md5Pass);
        //状态
        employee.setStatus(StatusConstant.ENABLE);
        //时间
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //操作人*/
        //todo 通过ThreadLocal获取当前线程里面的数据
        Long id = BaseContext.getCurrentId();
       /* employee.setCreateUser(id);
        employee.setUpdateUser(id);*/
        //保存
        employeeMapper.save(employee);
    }

    /**
     * 员工分页
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page pageInfo = employeeMapper.page(employeePageQueryDTO.getName());
        return new PageResult(pageInfo.getTotal(), pageInfo.getResult());
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        employee.setPassword("*****");
        return employee;
    }

    /**
     * 启用、禁用员工
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public void enableOrDisable(int status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id修改员工
     *
     * @return
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //将数据拷贝到employee
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     * @return
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Employee employee = new Employee();
        Long id = BaseContext.getCurrentId();
        //新密码
        String newPassword = passwordEditDTO.getNewPassword();
        //旧密码
        String oldPassword = passwordEditDTO.getOldPassword();
        //进行密码校验
        //1.输入的密码为空判断
        if (StringUtils.isEmpty(newPassword) && StringUtils.isEmpty(oldPassword)) {
            //输入的密码为空
            throw new PassWordIsNullException(MessageConstant.PWD_NOT_NULL);
        }
        //2.输入的原始密码和数据库不一样
        Employee byId = employeeMapper.findById(id);
        //数据库查询出的密码
        String password = byId.getPassword();

        if (!password.equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            throw new BaseException(MessageConstant.ORIGINAL_PWD_ERR);
        }
        //3.新旧密码是否一致
        if (oldPassword.equals(newPassword)) {
            throw new BaseException(MessageConstant.PWD_EQUALS_NULL);
        }
        //校验后修改密码
        //MD5加密
        String MD5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        employee.setId(id);
        employee.setPassword(MD5Password);
        employee.setUpdateTime(LocalDateTime.now());
        //执行修改
        employeeMapper.editPassword(employee);
    }

}
